//
//  MatchStickViewController.m
//  MoreFunTV
//
//  Created by admin on 14-11-1.
//  Copyright (c) 2014年 admin. All rights reserved.
//

#import "MatchStickViewController.h"
#import "AppDelegate.h"
#import "SimpleImageFetcher.h"
#import <Matchstick/Flint.h>
#import <math.h>
#import "UIImageView+AFNetworking.h"



@interface MatchStickViewController ()<VolumeChangeControllerDelegate> {
    NSTimeInterval _mediaStartTime;
    BOOL _currentlyDraggingSlider;
    BOOL _readyToShowInterface;
    BOOL _joinExistingSession;
   __weak MatchstickDeviceController *_matchstickController;
    
}
@property(strong, nonatomic) UIPopoverController *masterPopoverController;
@property (strong, nonatomic) UIImageView *thumbnailImage;
@property (strong, nonatomic) UILabel *flingingToLabel;
@property(strong, nonatomic)  UILabel *mediaTitleLabel;
@property(weak, nonatomic) NSTimer *updateStreamTimer;
@property(strong, nonatomic)  VolumeChangeController *volumeChange;

@property(nonatomic) UIBarButtonItem *currTime;
@property(nonatomic) UIBarButtonItem *totalTime;
@property(nonatomic) UISlider *slider;
@property(nonatomic) NSArray *playToolbar;
@property(nonatomic) NSArray *pauseToolbar;
@property(nonatomic) NSArray *notHaveButtonBar;

@end

@implementation MatchStickViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(id)initWithRealUrl:(NSString *)url
{
    _strReal = url;
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *imgSelf = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [imgSelf setUserInteractionEnabled:YES];
    imgSelf.backgroundColor = [UIColor clearColor];
    [imgSelf setImage:[UIImage imageNamed:@"background.png"]];
    [self.view addSubview:imgSelf];
    
    //获取通知中心
    NSNotificationCenter *notificationDismiss = [NSNotificationCenter defaultCenter];
    [notificationDismiss addObserver:self selector:@selector(dismiss:) name:@"dismiss" object:nil];
    [notificationDismiss addObserver:self selector:@selector(updateHistoryPlay) name:@"updateHistoryPlay" object:nil];
    
    AppDelegate *delegate = (AppDelegate *) [UIApplication sharedApplication].delegate;
    _matchstickController = delegate.matchstickDeviceController;
    _labName.text = _mediaToPlay ? _mediaToPlay.strTitle : _labNameString;
    
    _vlume = 1.00;
    _count = 0;
    
    //创建底部的view
    [self addView];
    
    //自定义标题
    [self customTitle];
    
    //添加显示界面
    [self addShowView];
    
    //添加控制界面
    [self addControlView];
    
    //播放列表添加
    [self addTablePlay];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _flagView = NO;
    _flagPrompt = NO;
    _set = [SetUpSingleton sharedSetUp];
    NSString *titleString = [SetUpSingleton sharedSetUp]._titleString;
    _set.detail.strTitle = titleString;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //执行耗时操作
        //查询投射记录信息
        NSMutableArray *arr = [DBDaoHelper selectAllTouShe];
        _arrPaly = [[NSMutableArray alloc]init];
        NSMutableArray *mutArr = [[NSMutableArray alloc]init];
        _arrCount = _set.arrCount;
        //上次操作不是添加列表
        if ([_set.strAddTouShe isEqual:@"NO"]) {
            for (int i = arr.count-1; i >= 0; i--) {
                [mutArr addObject:[arr objectAtIndex:i]];
            }
            _arrCount =  mutArr.count;
            _set.arrCount = _arrCount;
        }
        //是添加列表
        else{
            for (int i = _arrCount-1; i >= 0; i--) {
                [mutArr addObject:[arr objectAtIndex:i]];
            }
            
            for (int j = _arrCount; j < arr.count; j++) {
                [mutArr addObject:[arr objectAtIndex:j]];
            }
        }
        DetailInfo *playingInfo = [[DetailInfo alloc] init];
        bool found = false;
        for (int k = 0; k < mutArr.count; k ++) {
            //找到正在播放的视频
            if (found) {
                [_arrPaly addObject:[mutArr objectAtIndex:k]];
            }
            else {
                playingInfo = [mutArr objectAtIndex:k];
                //正在播放的视频
                if ([playingInfo.strTitle isEqualToString:self.mediaToPlay.strTitle]) {
                    found = true;
                }
                else {
                    [_arrPaly addObject:playingInfo];
                }
            }
        }
        //找到正在播放的视频
        if (found) {
            //将正在播放的视频放在列表最上面
            [_arrPaly insertObject:playingInfo atIndex:0];
            _set.count = 0;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //主线程更新UI
            _count = _set.count;
            [_tablePaly reloadData];
            _labName.text = _mediaToPlay ? _mediaToPlay.strTitle : _labNameString;
        });
    });
    
    _matchstickController.delegate = self;
    //设备未连接
    if (!_matchstickController.isConnected) {
        return;
    }
    _sound = [_matchstickController getStreamVolume]*kScreenHeight*(-50);
    // Assign ourselves as delegate ONLY in viewWillAppear of a view controller.
    //重置显示界面
    [self resetInterfaceElements];
    //读取正在播放的视频session
    if (_joinExistingSession == YES) {
        [self mediaNowPlaying];
    }
    [self configureView];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // I think we can safely stop the timer here
    [self.updateStreamTimer invalidate];
    self.updateStreamTimer = nil;
}

//创建底部的view
-(void)addView
{
    _viewSelf = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [_viewSelf setUserInteractionEnabled:YES];
    _viewSelf.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_viewSelf];
    
    //创建拖动手势对象
    _panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panClick:)];
    //关键语句，给self.view添加一个手势监测；
    _panRecognizer.delegate = self;
    [_viewSelf addGestureRecognizer:_panRecognizer];
    
    //创建点击手势对象
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    //设置点击次数
    tapRecognizer.numberOfTapsRequired = 1;
    tapRecognizer.delegate = self;
    //关键语句，给self.view添加一个点击手势监测；
    [_viewSelf addGestureRecognizer:tapRecognizer];
}

-(void)customTitle
{
    UIView *viewMa = [[UIView alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
    viewMa.backgroundColor = [UIColor clearColor];
    [_viewSelf addSubview:viewMa];
    
    //返回按钮
    UIButton *btnBack= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnBack.frame = CGRectMake(8, 0, 44, 44);
    btnBack.tintColor = [UIColor whiteColor];
    [btnBack setImage:[UIImage imageNamed:@"down.png"] forState:UIControlStateNormal];
    [btnBack setBackgroundColor:[UIColor clearColor]];
    [btnBack addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [viewMa addSubview:btnBack];
    
    //投射图标
    _btnTouShe = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnTouShe.frame = CGRectMake(kScreenWidth-44-8-40, 2, 40, 40);
    _btnTouShe.tintColor = [UIColor whiteColor];
    [_btnTouShe setImage:[UIImage imageNamed:@"toushe.png"] forState:UIControlStateNormal];
    [_btnTouShe addTarget:self action:@selector(clickTouShe) forControlEvents:UIControlEventTouchUpInside];
    [_btnTouShe setBackgroundColor:[UIColor clearColor]];
    [viewMa addSubview:_btnTouShe];
    
    //播放列表按钮
    UIButton *btnPlayTable = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnPlayTable.frame = CGRectMake(kScreenWidth-44-8, 0, 44, 44);
    btnPlayTable.tintColor = [UIColor whiteColor];
    [btnPlayTable setImage:[UIImage imageNamed:@"table.png"] forState:UIControlStateNormal];
    [btnPlayTable setBackgroundColor:[UIColor clearColor]];
    [btnPlayTable addTarget:self action:@selector(clickPlay) forControlEvents:UIControlEventTouchUpInside];
    [viewMa addSubview:btnPlayTable];
    
    UIView *viewline = [[UIView alloc]initWithFrame:CGRectMake(0, 43.5, kScreenWidth, 0.5)];
    viewline.backgroundColor = [UIColor colorWithWhite:0.854 alpha:1.000];
    [viewMa addSubview:viewline];
}

//添加显示界面
-(void)addShowView
{
    //滑动提示图片
    _imgPrompt = [[UIImageView alloc]initWithFrame:CGRectMake((kScreenWidth-30)/2, 64+6, 30, 30)];
    _imgPrompt.backgroundColor = [UIColor clearColor];
    [_imgPrompt setHidden:YES];
    [_viewSelf addSubview:_imgPrompt];
    
    //影片名称
    _labName = [[UILabel alloc]initWithFrame:CGRectMake(15, 100, kScreenWidth-15*2, 30)];
    _labName.backgroundColor = [UIColor clearColor];
    _labName.font = [UIFont systemFontOfSize:20.0f];
    _labName.textColor = [UIColor whiteColor];
    _labName.textAlignment = NSTextAlignmentCenter;
    [_viewSelf addSubview:_labName];
    
    //控制提示
    _labPrompt = [[UILabel alloc]initWithFrame:CGRectMake(15, (kScreenHeight-50)/2, kScreenWidth-15*2, 50)];
    _labPrompt.backgroundColor = [UIColor clearColor];
    _labPrompt.text = MyLocalizedString(@"control1");
    _labPrompt.font = [UIFont systemFontOfSize:15.0f];
    _labPrompt.textColor = [UIColor whiteColor];
    _labPrompt.numberOfLines = 2;
    _labPrompt.textAlignment = NSTextAlignmentCenter;
    [_viewSelf addSubview:_labPrompt];
    
    //控制按钮
    _btnControl = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnControl.frame = CGRectMake((kScreenWidth-70)/2, kScreenHeight-25-70, 70, 70);
    _btnControl.tintColor = [UIColor whiteColor];
    [_btnControl setImage:[UIImage imageNamed:@"control.png"] forState:UIControlStateNormal];
    [_btnControl setBackgroundColor:[UIColor clearColor]];
    _btnControl.layer.borderWidth = 1.0;
    _btnControl.layer.borderColor = [[UIColor clearColor]CGColor];
    _btnControl.layer.cornerRadius = 35.0;
    _btnControl.clipsToBounds = YES;
    [_btnControl addTarget:self action:@selector(clickControl:) forControlEvents:UIControlEventTouchUpInside];
    [_viewSelf addSubview:_btnControl];
}

//添加控制界面
-(void)addControlView
{
    _viewControl = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight-64)];
    _viewControl.backgroundColor = [UIColor clearColor];
    [_viewSelf addSubview:_viewControl];
    
    //自定义的播放控制按钮
    _controlView = [[PlayControlView alloc]initWithFrame:CGRectMake((kScreenWidth-216)/2, 86, 216, 216)];
    _controlView.backgroundColor = [UIColor clearColor];
    _controlView.delegate = self;
    [_viewControl addSubview:_controlView];
    
    //关闭按钮
    UIButton *btnClose = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnClose.frame = CGRectMake((kScreenWidth-70)/2, _viewControl.frame.size.height-25-70, 70, 70);
    btnClose.tintColor = [UIColor whiteColor];
    [btnClose setImage:[UIImage imageNamed:@"close@2x.png"] forState:UIControlStateNormal];
    [btnClose setBackgroundColor:[UIColor clearColor]];
    btnClose.layer.borderWidth = 1.20;
    btnClose.layer.borderColor = [[UIColor clearColor]CGColor];
    btnClose.layer.cornerRadius = 35.0;
    btnClose.clipsToBounds = YES;
    [btnClose addTarget:self action:@selector(clickClose) forControlEvents:UIControlEventTouchUpInside];
    [_viewControl addSubview:btnClose];

    //拉杆
    _slider = [[UISlider alloc]initWithFrame:CGRectMake(15, 86+216+(_viewControl.frame.size.height-86-216-30-70)/2,kScreenWidth-15*2 , 20)];
    _slider.value = 0.0;//默认值
    [_slider setMinimumTrackImage:[UIImage imageNamed:@"huagan"] forState:UIControlStateNormal];
    [_slider setThumbImage:[UIImage imageNamed:@"lagan.png"] forState:UIControlStateNormal];;
    _slider.continuous = YES;//滑动事件触发  边滑动边触发
    _slider.backgroundColor = [UIColor clearColor];
    [_slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self
                    action:@selector(onTouchDown:)
          forControlEvents:UIControlEventTouchDown];
    [self.slider addTarget:self
                    action:@selector(onTouchUpInside:)
          forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self
                    action:@selector(onTouchUpOutside:)
          forControlEvents:UIControlEventTouchUpOutside];
    [self.slider addTarget:self
                    action:@selector(onTouchUpOutside:)
          forControlEvents:UIControlEventTouchCancel];
    [_viewControl addSubview:_slider];
    
    //值显示
    _labTotalValue = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth-95, _slider.frame.origin.y+20+5, 80, 20)];
    _labTotalValue.backgroundColor = [UIColor clearColor];
    _labTotalValue.font = [UIFont systemFontOfSize:16.0f];
    _labTotalValue.text = [NSString stringWithFormat:@"%.2f",_slider.maximumValue];
    _labTotalValue.textColor = [UIColor whiteColor];
    _labTotalValue.textAlignment = NSTextAlignmentRight;
    [_viewControl addSubview:_labTotalValue];
    
    _labCurrlValue = [[UILabel alloc]initWithFrame:CGRectMake(15, _slider.frame.origin.y+20+5, 80, 20)];
    _labCurrlValue.backgroundColor = [UIColor clearColor];
    _labCurrlValue.font = [UIFont systemFontOfSize:16.0f];
    _labCurrlValue.text = [NSString stringWithFormat:@"%.2f",_slider.maximumValue];
    _labCurrlValue.textColor = [UIColor whiteColor];
    _labCurrlValue.textAlignment = NSTextAlignmentLeft;
    [_viewControl addSubview:_labCurrlValue];
}

//播放列表添加
-(void)addTablePlay
{
    //列表
    _tablePaly = [[UITableView alloc]initWithFrame:CGRectMake(kScreenWidth, 20, kScreenWidth-70, kScreenHeight-20) style:UITableViewStylePlain];
    _tablePaly.showsVerticalScrollIndicator = NO;//隐藏纵向滚动条
    _tablePaly.delegate = self;
    _tablePaly.dataSource = self;
    _tablePaly.bounces = NO;
    [_tablePaly setSeparatorColor:[UIColor whiteColor]];
    [_tablePaly setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];//[UIColor colorWithRed:55.0/255.0 green:55.0/255.0 blue:55.0/255.0 alpha:1.000]];
    [self.view addSubview:_tablePaly];
    
    //列表头部view
    UIView *viewHeader =[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-70, 45)];
//    viewHeader.backgroundColor = [UIColor colorWithRed:55.0/255.0 green:55.0/255.0 blue:55.0/255.0 alpha:1.000];
    _tablePaly.tableHeaderView = viewHeader;
    
    //列表名
    UILabel *labTitle  = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, viewHeader.frame.size.width/2, 45)];
    labTitle.backgroundColor = [UIColor clearColor];
    labTitle.font = [UIFont boldSystemFontOfSize:19.0f];
    labTitle.text = @"  视频列表";
    labTitle.textColor = [UIColor whiteColor];
    labTitle.textAlignment = NSTextAlignmentLeft;
    [viewHeader addSubview:labTitle];
    
    //编辑按钮
    UIButton *btnEdit = [UIButton buttonWithType:UIButtonTypeCustom];
    btnEdit.frame = CGRectMake(kScreenWidth-70-48-10, 7, 48, 30);
    btnEdit.titleLabel.font = [UIFont boldSystemFontOfSize:16.0f];
    [btnEdit setBackgroundImage:[UIImage imageNamed:@"kuang.png"] forState:UIControlStateNormal];
    [btnEdit setTitle:MyLocalizedString(@"edit") forState:UIControlStateNormal];
    [btnEdit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnEdit setBackgroundColor:[UIColor clearColor]];
    [btnEdit addTarget:self action:@selector(clickEdit:) forControlEvents:UIControlEventTouchUpInside];
    [viewHeader addSubview:btnEdit];
    
    UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(15, 44.5, kScreenWidth-70-15, 0.5)];
    viewLine.backgroundColor = [UIColor whiteColor];
    [viewHeader addSubview:viewLine];
}

//播放列表按钮
-(void)clickPlay
{
    if (_flag == NO){
        _flag = YES;
        [UIView animateWithDuration:0.25f animations:^{
            _tablePaly.frame = CGRectMake(70, 20, kScreenWidth-70, kScreenHeight-20);
            _viewSelf.frame = CGRectMake(-kScreenWidth+70, 0, kScreenWidth, kScreenHeight);
        }];
    }
    else
    {
        _flag = NO;
        [UIView animateWithDuration:0.25f animations:^{
            _tablePaly.frame = CGRectMake(kScreenWidth, 20, kScreenWidth-70, kScreenHeight-20);
            _viewSelf.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        }];
    }
}

//控制按钮
-(void)clickControl:(UIButton *)sender
{
    _flagView = YES;
    [UIView animateWithDuration:0.25f animations:^{
        [_btnControl setHidden:YES];
        [_labPrompt setHidden:YES];
        _viewControl.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight-64);
        _labName.frame = CGRectMake(15, 26, kScreenWidth-15*2, 30);
        [_viewControl addSubview:_labName];
    }];
}

//投射按钮
-(void)clickTouShe{
    //投射按钮调用的方法
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myDevice" object:nil userInfo:nil];
}

//通知事件
-(void)dismiss:(NSNotification *)notification{
    [self updateHistoryPlay];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

//关闭按钮
-(void)clickClose
{
    _flagView = NO;
    [UIView animateWithDuration:0.25f animations:^{
        _viewControl.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight-64);
        _labName.frame = CGRectMake(15, 100, kScreenWidth-15*2, 30);
        [_viewSelf addSubview:_labName];
        [_labPrompt setHidden:NO];
        [_btnControl setHidden:NO];
    }];
}

//滑动手势
-(void)panClick:(UIPanGestureRecognizer *)sender
{
    _imgPrompt.frame = CGRectMake((kScreenWidth-30)/2, 64+6, 30, 30);
//    CGPoint point2 = [sender translationInView:_viewSelf];
    
    //修正方向
    CGPoint point = [sender locationInView:_viewSelf];
    if (sender.state == UIGestureRecognizerStateBegan){
        _pontXStart = point.x;
        _pontYStart = point.y;
        _pontXLast = 0;
        _pontYLast = 0;
        _zhi = _matchstickController.streamPosition*kScreenWidth/(0.01*_matchstickController.streamDuration);
    }
    else if (sender.state == UIGestureRecognizerStateChanged) {
        _pontYStop = point.y;
        _pontXStop = point.x;
        float pianYiX = _pontXStop-_pontXStart;
        float pianYiY = _pontYStop-_pontYStart;
        
        if (_flagView == NO && _flag == NO )
        {
            _sound = _sound + pianYiY;
            _zhi = _zhi + pianYiX;
            if (pianYiX < 0) {
                pianYiX = pianYiX *(-1);
            }
            if (pianYiY < 0){
                pianYiY = pianYiY *(-1);
            }
            //需要修正方向
            if (_pontYLast > pianYiY) {
                _pontYLast = 0;
                _pontYStart = point.y;
            }
            else {
                _pontYLast = pianYiY;
            }
            //需要修正方向
            if (_pontXLast > pianYiX) {
                _pontXLast = 0;
                _pontXStart = point.x;
            }
            else {
                _pontXLast = pianYiX;
            }
            
            if ((pianYiY > pianYiX && _pontYStop > _pontYStart) || (pianYiY > pianYiX && _pontYStop < _pontYStart))
            {
                //修正方向
                _pontXStart = point.x;
                
                float ssssound;
                ssssound = _sound*0.02/kScreenHeight*(-1);
                //音量调节
                [_imgPrompt setHidden:NO];
                [_imgPrompt setImage:[UIImage imageNamed:@"souhu_player_volume.png"]]; 
                if (ssssound < 0) {
                    _sound = 0;
                    [_imgPrompt setImage:[UIImage imageNamed:@"souhu_player_silence.png"]];
                    [_matchstickController setStreamVolume:0];
                    _labName.text = [NSString stringWithFormat:@"%@0％",MyLocalizedString(@"control2")];
                }
                else if (ssssound > 1.0){
                    _sound = kScreenHeight*50*(-1);
                    [_matchstickController setStreamVolume:1.0];
                    _labName.text = [NSString stringWithFormat:@"%@100％",MyLocalizedString(@"control2")];
                }
                else{
                    [_matchstickController setStreamVolume:ssssound];
                    _labName.text = [NSString stringWithFormat:@"%@%.f％",MyLocalizedString(@"control2"),ssssound*100];
                }
                
                NSString *strSound = [NSString stringWithFormat:@"%.1f",ssssound];
                _vlume = [strSound floatValue];
            }
            else if ((pianYiX > pianYiY && _pontXStop > _pontXStart) || (pianYiX > pianYiY && _pontXStop < _pontXStart))
            {
                //修正方向
                _pontYStart = point.y;
                
                [_matchstickController setPlaybackPercent:_zhi*0.01/kScreenWidth];
                [self.slider setValue:(_zhi*0.01/kScreenWidth) animated:YES];
                _labCurrlValue.text =
                [self getFormattedTime:(_zhi*0.01/kScreenWidth* _matchstickController.streamDuration)];
                [_imgPrompt setHidden:NO];
                
                if (pianYiX > pianYiY && _pontXStop > _pontXStart) {
                    [_imgPrompt setImage:[UIImage imageNamed:@"souhu_player_forward.png"]];
                }
                else if (pianYiX > pianYiY && _pontXStop < _pontXStart){
                    [_imgPrompt setImage:[UIImage imageNamed:@"souhu_player_backward.png"]];
                }
                
                if (_zhi*0.01/kScreenWidth* _matchstickController.streamDuration < 0) {
                    _labName.text = [NSString stringWithFormat:@"00:00/%@",[self getFormattedTime:_matchstickController.streamDuration]];
                }
                else if (_zhi*0.01/kScreenWidth* _matchstickController.streamDuration > _matchstickController.streamDuration){
                    _labName.text = [NSString stringWithFormat:@"%@/%@",[self getFormattedTime:_matchstickController.streamDuration],[self getFormattedTime:_matchstickController.streamDuration]];
                }
                else{
                    _labName.text = [NSString stringWithFormat:@"%@/%@",[self getFormattedTime:(_zhi*0.01/kScreenWidth* _matchstickController.streamDuration)],[self getFormattedTime:_matchstickController.streamDuration]];
                }
            }
        }
    }
    else if (sender.state == UIGestureRecognizerStateEnded) {
        if (_flag == YES){
            [UIView animateWithDuration:0.5f animations:^{
                _flag = NO;
                _tablePaly.frame = CGRectMake(kScreenWidth, 20, kScreenWidth-70, kScreenHeight-20);
                _viewSelf.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            }];
        }
        else if (_flagView == NO && _flag == NO )
        {
            [NSThread detachNewThreadSelector:@selector(jinDuTunPian) toTarget:self withObject:nil];
        }
    }
}

//进度图的显示 音量图 开始暂停图的提示
-(void)jinDuTunPian{
    sleep(1.50);
    [_imgPrompt setHidden:YES];
    _labName.text = _mediaToPlay ? _mediaToPlay.strTitle : _labNameString;
}

//拉杆值的变化
-(void)sliderValueChanged:(UISlider *)slider
{
    float pctThrough = [self.slider value];
    if (_matchstickController.streamDuration > 0) {
        _labCurrlValue.text =
        [self getFormattedTime:(pctThrough * _matchstickController.streamDuration)];
        _labName.text = [NSString stringWithFormat:@"%@/%@",[self getFormattedTime:(pctThrough * _matchstickController.streamDuration)],[self getFormattedTime:_matchstickController.streamDuration]];
    }
//    [NSThread detachNewThreadSelector:@selector(jinDuTunPian) toTarget:self withObject:nil];
}

- (void)touchIsFinished {
    [_matchstickController setPlaybackPercent:[self.slider value]];
    _currentlyDraggingSlider = NO;
    
    //进度图的显示 音量图 开始暂停图的提示
    [_imgPrompt setHidden:YES];
    _labName.text = _mediaToPlay ? _mediaToPlay.strTitle : _labNameString;
}

- (void)onTouchUpInside:(id)sender {
    NSLog(@"Touch up inside");
    [self touchIsFinished];
}

- (void)onTouchUpOutside:(id)sender {
    NSLog(@"Touch up outside");
    [self touchIsFinished];
}

//更新显示历史记录
-(void)updateHistoryPlayShow {
    DetailInfo *dea = [[DetailInfo alloc]init];
    dea = _mediaToPlay;
    //获取到主键
    if (dea.strPlayId) {
        NSLog(@"获取主键:%@",dea.strPlayId);
        //获取当前时间
        NSDate *datenow = [[NSDate alloc]init];
        dea.dateTime = datenow;
        //更新播放进度
        dea.strHistoryTime = nil;
        dea.strPlaySource = @"touPlay";
        [DBDaoHelper updatePlay:dea];
    }
    else {
        NSLog(@"获取主键失败!!!");
    }
}

//更新播放进度
-(void)updateHistoryPlay {
    DetailInfo *dea = [[DetailInfo alloc]init];
    dea = _mediaToPlay;
    //获取到主键
    if (dea.strPlayId) {
        NSLog(@"获取主键:%@",dea.strPlayId);
        //获取当前时间
        NSDate *datenow = [[NSDate alloc]init];
        dea.dateTime = datenow;
        //更新播放进度
        dea.strHistoryTime = _labCurrlValue.text;
        dea.strPlaySource = @"touPlay";
        [DBDaoHelper updatePlay:dea];
    }
    else {
        NSLog(@"获取主键失败!!!");
    }
}

//cell点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //更新播放进度
    [self updateHistoryPlay];
    //切换标识位
    _flag = NO;
    [UIView animateWithDuration:0.25f animations:^{
        _tablePaly.frame = CGRectMake(kScreenWidth, 20, kScreenWidth-70, kScreenHeight-20);
        _viewSelf.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
    //点击切换
    _count = indexPath.row;
    _zhi = 0;
    _sound = [_matchstickController getStreamVolume]*kScreenHeight*(-50);// 0;
    if (_count >= 0 && _count < _arrPaly.count) {
        _set.count = _count;
        _mediaToPlay = [_arrPaly objectAtIndex:_count];
    }
    else{
        if (_arrPaly.count != 0) {
            _count = _arrPaly.count-1;
            _set.count = _count;
            _mediaToPlay = [_arrPaly objectAtIndex:_count];
        }
    }
    self.strAllRealUrl = _mediaToPlay.strAllURL;
    _strReal = _mediaToPlay.strRealUrl;
    _flagBtn = NO;
    [_matchstickController pauseFlingMedia:NO];
    [_controlView.btnPlay setImage:[UIImage imageNamed:@"playplay.png"] forState:UIControlStateNormal];//播放
    //切换播放
    if (![_labName.text isEqualToString:_mediaToPlay.strTitle]) {
        //切换投射
        [_matchstickController stopFlingMedia];
        [self setMediaToPlay:_mediaToPlay];
        [self resetInterfaceElements];
        [self configureView];
        [_tablePaly reloadData];
        //更新播放记录信息
        [self updateHistoryPlayShow];
    }
}

//列表每行显示的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"firstTable";
    //row 代表列表的那一行
    int row = (int)[indexPath row];
    //获取cell row ＝ 0 获取不到 进入创建cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:identifier];
        [cell setBackgroundColor:[UIColor clearColor]];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:18.0f];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.showsReorderControl = YES;
    }
    DetailInfo *det = [_arrPaly objectAtIndex:row];
    if (row == _count) {
        //如果正在播放  黄色字体显示
        NSRange rangeStr = [det.strTitle rangeOfString:det.strTitle];
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:det.strTitle];
        [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.988 green:0.987 blue:0.002 alpha:1.000] range:rangeStr];
        cell.textLabel.attributedText = AttributedStr;
    }
    else{
        NSRange rangeStr = [det.strTitle rangeOfString:det.strTitle];
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:det.strTitle];
        [AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:rangeStr];
        cell.textLabel.attributedText = AttributedStr;
    }
    return cell;
}


/*删除用到的函数*/
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //cell上的按钮
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        DetailInfo *detailIn = [_arrPaly objectAtIndex:indexPath.row];
        //删除数据库中的数据
        [DBDaoHelper deleteTouShe:detailIn];
        //删除数组里的数据
        [_arrPaly removeObjectAtIndex:[indexPath row]];
        //重新加载cell  withRowAnimation为删除时的动画样式
        //删除对应数据的cell
        [_tablePaly deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
        
        if (indexPath.row < _count) {
            _count = _count-1;
        }
        else if (indexPath.row == _count) {
            //更新播放进度
            [self updateHistoryPlay];
            _zhi = 0;
            _sound = [_matchstickController getStreamVolume]*kScreenHeight*(-50);// 0;
            if (_count >= 0 && _count < _arrPaly.count) {
                _set.count = _count;
                _mediaToPlay = [_arrPaly objectAtIndex:_count];
            }
            else{
                if (_arrPaly.count != 0) {
                    _count = 0;
                    _set.count = _count;
                    _mediaToPlay = [_arrPaly objectAtIndex:_count];
                }
            }
            _strReal = _mediaToPlay.strRealUrl;
            self.strAllRealUrl = _mediaToPlay.strAllURL;
            _flagBtn = NO;
            [_matchstickController pauseFlingMedia:NO];
            //播放
            [_controlView.btnPlay setImage:[UIImage imageNamed:@"playplay.png"] forState:UIControlStateNormal];
            
            //切换投射
//            [_matchstickController stopFlingMedia];
//            [self setMediaToPlay:_mediaToPlay];
//            [self resetInterfaceElements];
//            [self configureView];
            [_tablePaly reloadData];
        }
        
        if (_arrPaly.count == 0) {
            _labNameString = _labName.text;
            _strReal = @"";
//            _mediaToPlay = nil;
            [self resetInterfaceElements];
            [self configureView];
//            [_imgSelf setImage:[UIImage imageNamed:@"background.png"]];
        }
        
        [_tablePaly reloadData];
        _arrCount = _arrPaly.count;
        _set.count = _count;
        _set.arrCount = _arrCount;
    }
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    // NSLog(@"from(%i)-to(%i)", sourceIndexPath.row, destinationIndexPath.row);
    // 更换数据的顺序
    id object = [_arrPaly objectAtIndex:sourceIndexPath.row];
    [_arrPaly removeObjectAtIndex:sourceIndexPath.row];
    [_arrPaly insertObject:object atIndex:destinationIndexPath.row];
    [_arrPaly exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
}

//编辑按钮事件
-(void)clickEdit:(UIButton *)sender
{
    [_tablePaly setEditing:!_tablePaly.editing animated:YES];
    if (_tablePaly.editing)
    {
        [sender setTitle:MyLocalizedString(@"finish") forState:UIControlStateNormal];
    }
    else
    {
        [sender setTitle:MyLocalizedString(@"edit") forState:UIControlStateNormal];
    }
}

//点击事件的方法
-(void)tapClick:(UITapGestureRecognizer *)recognizer{
    _imgPrompt.frame = CGRectMake((kScreenWidth-20)/2, 64+12, 20, 20);
    if (_flagView == NO && _flag == NO) {
        if (_flagPrompt == NO && _flagBtn == NO) {
            _flagPrompt = YES;
            _flagBtn = YES;
            [_controlView changBtnImge:YES];
            [_imgPrompt setHidden:NO];
            [_imgPrompt setImage:[UIImage imageNamed:@"playfilm.png"]];//暂停
            [_matchstickController pauseFlingMedia:YES];
        }
        else{
            _flagPrompt = NO;
            _flagBtn = NO;
            [_controlView changBtnImge:NO];
            [_imgPrompt setHidden:NO];
            [_imgPrompt setImage:[UIImage imageNamed:@"playplay.png"]];//开始
            [_matchstickController pauseFlingMedia:NO];
        }
        [NSThread detachNewThreadSelector:@selector(jinDuTunPian) toTarget:self withObject:nil];
    }
}


//播放控制自定义协议方法
-(void)playControlView:(PlayControlView *)playView ButtonControl:(UIButton *)btn
{
    switch (btn.tag) {
        case 10455://播放按钮
            if (_flagBtn == NO) {
                _flagBtn = YES;
                [_matchstickController pauseFlingMedia:YES];
                [btn setImage:[UIImage imageNamed:@"playfilm.png"] forState:UIControlStateNormal];//暂停
            }
            else{
                _flagBtn = NO;
                [_matchstickController pauseFlingMedia:NO];
                [btn setImage:[UIImage imageNamed:@"playplay.png"] forState:UIControlStateNormal];//播放
            }
            break;
        case 10222:{//音量加
            _vlume = _vlume + 0.10;
            if (_vlume < 0) {
                _vlume = 0;
            }
            else if (_vlume > 1.0){
                _vlume = 1.0;
            }
            [_matchstickController setStreamVolume:_vlume];
            _labName.text = [NSString stringWithFormat:@"%@%.f％",MyLocalizedString(@"control2"),_vlume*100];
            _sound = _vlume*kScreenHeight*(-1)*50;
            [NSThread detachNewThreadSelector:@selector(jinDuTunPian) toTarget:self withObject:nil];
        }
            break;
        case 10112:{//音量减
            _vlume = _vlume - 0.10;
            if (_vlume < 0) {
                _vlume = 0;
                [_imgPrompt setImage:[UIImage imageNamed:@"souhu_player_silence.png"]];
            }
            else if (_vlume > 1.0){
                _vlume = 1.0;
            }
            [_matchstickController setStreamVolume:_vlume];
            _labName.text = [NSString stringWithFormat:@"%@%.f％",MyLocalizedString(@"control2"),_vlume*100];
            _sound = _vlume*kScreenHeight*(-1)*50;
            [NSThread detachNewThreadSelector:@selector(jinDuTunPian) toTarget:self withObject:nil];
        }
            break;
        case 10337:{//上一个
            //加入判断，使不能循环播放
            if (_count == 0 || _arrPaly.count==0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfoi") delegate:nil cancelButtonTitle:MyLocalizedString(@"sure") otherButtonTitles:nil];
                [alert show];
                return;
            }
            //更新播放进度
            [self updateHistoryPlay];
            _count--;
            _zhi = 0;
            _sound = [_matchstickController getStreamVolume]*kScreenHeight*(-50);// 0;
            if (_count >= 0 && _count < _arrPaly.count) {
                _set.count = _count;
                _mediaToPlay = [_arrPaly objectAtIndex:_count];
            }
            else{
                if (_arrPaly.count != 0) {
                    _count = _arrPaly.count-1;
                    _set.count = _count;
                    _mediaToPlay = [_arrPaly objectAtIndex:_count];
                }
            }
            self.strAllRealUrl = _mediaToPlay.strAllURL;
            _strReal = _mediaToPlay.strRealUrl;
            _flagBtn = NO;
            [_matchstickController pauseFlingMedia:NO];
            [_controlView.btnPlay setImage:[UIImage imageNamed:@"playplay.png"] forState:UIControlStateNormal];//播放
            
            //切换投射
            [_matchstickController stopFlingMedia];
            [self setMediaToPlay:_mediaToPlay];
            [self resetInterfaceElements];
            [self configureView];
            [_tablePaly reloadData];
//            if (![self.mediaToPlay.strThumbnail isKindOfClass:[NSNull class]] && self.mediaToPlay.strThumbnail.length > 0)
//            {//不是空字符串的
//                [_imgSelf setImageWithURL:[NSURL URLWithString:deta.strThumbnail]];
//            }
//            else{//空串
//                [_imgSelf setImage:[UIImage imageNamed:@"background.png"]];
//            }
        }
            break;
        default:{//下一个
            //加入判断，使不能循环播放
            if (_count == _arrPaly.count-1 || _arrPaly.count==0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:MyLocalizedString(@"alertinfo1") message:MyLocalizedString(@"alertinfoj") delegate:nil cancelButtonTitle:MyLocalizedString(@"sure") otherButtonTitles:nil];
                [alert show];
                return;
            }
            //更新播放进度
            [self updateHistoryPlay];
            _count++;
            _zhi = 0;
            _sound = [_matchstickController getStreamVolume]*kScreenHeight*(-50);// 0;
            if (_count >= 0 && _count < _arrPaly.count) {
                _set.count = _count;
                _mediaToPlay = [_arrPaly objectAtIndex:_count];
            }
            else{
                if (_arrPaly.count != 0) {
                    _count = 0;
                    _set.count = _count;
                    _mediaToPlay = [_arrPaly objectAtIndex:_count];
                }
            }
            _strReal = _mediaToPlay.strRealUrl;
            self.strAllRealUrl = _mediaToPlay.strAllURL;
            _flagBtn = NO;
            [_matchstickController pauseFlingMedia:NO];
            [_controlView.btnPlay setImage:[UIImage imageNamed:@"playplay.png"] forState:UIControlStateNormal];//播放

            //切换投射
            [_matchstickController stopFlingMedia];
            [self setMediaToPlay:_mediaToPlay];
            [self resetInterfaceElements];
            [self configureView];
            [_tablePaly reloadData];
//            if (![self.mediaToPlay.strThumbnail isKindOfClass:[NSNull class]] && self.mediaToPlay.strThumbnail.length > 0)
//            {//不是空字符串的
//                [_imgSelf setImageWithURL:[NSURL URLWithString:detail.strThumbnail]];
//            }
//            else{//空串
//                [_imgSelf setImage:[UIImage imageNamed:@"background.png"]];
//            }
        }
            break;
    }
}

- (void) deviceManager:(MSFKDeviceManager *)deviceManager
volumeDidChangeToLevel:(float)volumeLevel
               isMuted:(BOOL)isMuted {
//    NSLog(@"New volume level of %f reported!", volumeLevel);
    self.deviceVolume = volumeLevel;
    self.deviceMuted = isMuted;
}

//列表每行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrPaly.count;
}

/*改变删除按钮的title*/
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return MyLocalizedString(@"delete");
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//返回按钮
-(void)clickBack
{
    _set = [SetUpSingleton sharedSetUp];
    _matchstickController.delegate = self;
    if (_matchstickController.isConnected) {
        UIButton *matchstickButton = (UIButton *) _matchstickController.matchstickBarButton.customView;
        [matchstickButton setImage:[UIImage imageNamed:@"playing.png"] forState:UIControlStateNormal];
//        NSLog(@"_____________playing.png");
        _set.strHidden = @"NO";
    }
    else{
        _set.strHidden = @"YES";
    }
    _set.detail = self.mediaToPlay;
    _set.strTouSheURL = _strReal;
    _set.strAllTouSheURL = _strAllRealUrl;
    
    _set._titleString = self.mediaToPlay.strTitle;
//    NSLog(@"_______________%@",[SetUpSingleton sharedSetUp]._titleString);
    
//    [_matchstickController stopFlingMedia];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BtnSetHidden" object:nil userInfo:nil];
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}


- (void)setMediaToPlay:(DetailInfo *)newDetailItem {
    [self setMediaToPlay:newDetailItem withStartingTime:0];
}

- (void)setMediaToPlay:(DetailInfo *)newMedia withStartingTime:(NSTimeInterval)startTime {
    _mediaStartTime = startTime;
    if (_mediaToPlay != newMedia) {
        _mediaToPlay = newMedia;
//        NSLog(@"%@",_mediaToPlay);
        // Update the view.
        [self configureView];
    }
}

- (void)resetInterfaceElements {
    _labTotalValue.text = @"";
    _labCurrlValue.text = @"";
    [self.slider setValue:0];
    _currentlyDraggingSlider= NO;
    _readyToShowInterface = NO;
}

- (void)mediaNowPlaying {
    _readyToShowInterface = YES;
    [self updateInterfaceFromFling:nil];
}

- (void)updateInterfaceFromFling:(NSTimer *)timer {
    [_matchstickController updateStatsFromDevice];
    if (!_readyToShowInterface){
        NSLog(@"updateInterfaceFromFling2");
        if (timer == nil) {//_strReal.length != 0) {
            [Loading showLoadingTouShe:self.view];
        }
        return;
    }
    NSLog(@"updateInterfaceFromFling");
    
    //_matchstickController.streamDuration > 0 && !_currentlyDraggingSlider
    if (_matchstickController.streamDuration > 0) {
        NSLog(@"updateInterfaceFromFling3");
        [Loading hiddonLoadingWithView:self.view];
        _labCurrlValue.text = [self getFormattedTime:_matchstickController.streamPosition];
        _labTotalValue.text = [self getFormattedTime:_matchstickController.streamDuration];

        [self.slider
         setValue:(_matchstickController.streamPosition / _matchstickController.streamDuration)
         animated:YES];
        
//        if (number < _arrUrl.count)
//        {
//            if ((int)_matchstickController.streamPosition == (int)_matchstickController.streamDuration && done==YES)
//            {
//                _zhi = 0;
//                _sound = 0;
//                NSString *str= [_arrUrl objectAtIndex:number];
//                NSURL *url = [NSURL URLWithString:str];
//                [_matchstickController loadMedia:url
//                                    thumbnailURL:nil
//                                           title:self.mediaToPlay.strTitle
//                                        subtitle:nil
//                                        mimeType:nil
//                                       startTime:_mediaStartTime
//                                        autoPlay:YES];
//                done =NO;
//                number++;
//            }else {
//                done = YES;
//            }
//        }
        
        if ((int)_matchstickController.streamPosition == (int)_matchstickController.streamDuration && done==YES)
        {
            //判断播放到最后一部视频
            if (_count == _arrPaly.count-1) {
//                self.mediaToPlay.strTitle =
                return;
            }
            _count++;
            _zhi = 0;
            _sound = [_matchstickController getStreamVolume]*kScreenHeight*(-50);// 0;
            if (_count >= 0 && _count < _arrPaly.count) {
                _set.count = _count;
                _mediaToPlay = [_arrPaly objectAtIndex:_count];
            }
            else{
                if (_arrPaly.count != 0) {
                    _count = 0;
                    _set.count = _count;
                    _mediaToPlay = [_arrPaly objectAtIndex:_count];
                }
            }
            _strReal = _mediaToPlay.strRealUrl;
            self.strAllRealUrl = _mediaToPlay.strAllURL;
            _labName.text = _mediaToPlay ? _mediaToPlay.strTitle : _labNameString;
            //切换投射
            [self resetInterfaceElements];
            NSURL *url = [NSURL URLWithString:_strReal];
            [_matchstickController loadMedia:url
                                thumbnailURL:nil
                                       title:_mediaToPlay.strTitle
                                    subtitle:nil
                                    mimeType:nil
                                   startTime:_mediaStartTime
                                    autoPlay:YES];
            [_tablePaly reloadData];
        }
    }
}

// Little formatting option here

- (NSString *)getFormattedTime:(NSTimeInterval)timeInSeconds {
    NSInteger seconds = (NSInteger) round(timeInSeconds);
    NSInteger hours = seconds / (60 * 60);
    seconds %= (60 * 60);
    
    NSInteger minutes = seconds / 60;
    seconds %= 60;
    
    if (hours > 0) {
        return [NSString stringWithFormat:@"%ld:%02ld:%02ld", (long)hours, (long)minutes, (long)seconds];
    }
    else {
        return [NSString stringWithFormat:@"%ld:%02ld", (long)minutes, (long)seconds];
    }
}

- (void)configureView {
    number = 1;
    done = YES;
    if (self.strAllRealUrl.length != 0) {
        NSDictionary *urlDic =
        [NSJSONSerialization JSONObjectWithData: [self.strAllRealUrl dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: nil];
        _arrUrl = [urlDic objectForKey:@"hd"];
//        NSLog(@"真实地址得数组%d",_arrUrl.count);
    }
    
    NSURL *url = [NSURL URLWithString:_strReal];//播放地址
    if (_mediaToPlay && _matchstickController.isConnected) {
        _labName.text = _mediaToPlay ? _mediaToPlay.strTitle : _labNameString;

        // If the newMedia is already playing, join the existing session.
        if (![self.mediaToPlay.strTitle isEqualToString:[_matchstickController.mediaInformation.metadata stringForKey:kMSFKMetadataKeyTitle]] || !_matchstickController.isPlayingMedia) {
            //Fling the movie!!
            [_matchstickController loadMedia:url
                                thumbnailURL:nil
                                       title:self.mediaToPlay.strTitle
                                    subtitle:nil
                                    mimeType:nil
                                   startTime:_mediaStartTime
                                    autoPlay:YES];
            _joinExistingSession = NO;
        } else {
            NSLog(@"________________joinExistingSession");
            _joinExistingSession = YES;
            [self mediaNowPlaying];
        }
        
        // Start the timer
        if (self.updateStreamTimer) {
            [self.updateStreamTimer invalidate];
            self.updateStreamTimer = nil;
        }
        
        [_matchstickController updateStatsFromDevice];
        if (!_readyToShowInterface){
            if (_strReal.length != 0) {
                [Loading showLoadingTouShe:self.view];
            }
        }
        
        self.updateStreamTimer =
        [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(updateInterfaceFromFling:)
                                       userInfo:nil
                                        repeats:YES];
        //超时处理
        [NSTimer scheduledTimerWithTimeInterval:60.0
                                         target:self
                                       selector:@selector(stopInterfaceFromFling:)
                                       userInfo:nil
                                        repeats:NO];
    }
}

- (void)stopInterfaceFromFling:(NSTimer *)timer {
    NSLog(@"updateInterfaceFromFling3");
    [Loading hiddonLoadingWithView:self.view];
}

#pragma mark - On - screen UI elements
- (void)pauseButtonClicked:(id)sender {
    [_matchstickController pauseFlingMedia:YES];
}

- (void)playButtonClicked:(id)sender {
    [_matchstickController pauseFlingMedia:NO];
}

// Unsed, but if you wanted a stop, as opposed to a pause button, this is probably
// what you would call
- (void)stopButtonClicked:(id)sender {
    [_matchstickController stopFlingMedia];
}

- (void)onTouchDown:(id)sender {
    _currentlyDraggingSlider = YES;
}


- (void)didReceiveMediaStateChange {
    _readyToShowInterface = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 * Called when Matchstick devices are discoverd on the network.
 */
- (void)didDiscoverDeviceOnNetwork
{
    
}

/**
 * Called when connection to the device was established.
 *
 * @param device The device to which the connection was established.
 */
- (void)didConnectToDevice:(MSFKDevice *)device
{
    
}

/**
 * Called when connection to the device was closed.
 */
- (void)didDisconnect
{
    
}

/**
 * Called when the playback state of media on the device changes.
 */
//- (void)didReceiveMediaStateChange
//{
//    
//}

/**
 * Called to display the modal device view controller from the fling icon.
 */
- (void)shouldDisplayModalDeviceController
{
    
}

/**
 * Called to display the remote media playback view controller.
 */
- (void)shouldPresentPlaybackController
{
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
